/*
 * Conn.cpp
 *
 *   Created on: 2010-3-24     
 *  Description: 
 *    Copyright: 2010 @ ICT Li Heyuan
 */

#include "../../include/server/Server.h"
#include "../../include/conn/Conn.h"
#include "../../include/json_cpp/value.h"
#include "../../include/util/JsonRpcException.h"
using Json::Value;

#include <stdexcept>
#include <iostream>
using std::runtime_error;
using std::cout;
using std::endl;

Conn::Conn(Server* server, int sock, const EasyAddr &addr) :
	_server(server), _addr(addr), _sock(sock), _exeSuccess(false),
			_isNotification(false)
{
	_startTime = time(NULL);
	_safeDel = false;
}

Conn::~Conn()
{
}

void Conn::callMethod()
{
	try
	{
		//先找有没有这个方法
		string method_str = _jsonReq["method"].asString();

		//检查method不能为空
		if (method_str.empty())
		{
			throw JsonRpcException("Method can't be null.");
		}

		RpcMethod *method = _server->findMethod(method_str);

		//检查method是否没有找到
		if (method == NULL)
		{
			throw JsonRpcException("Method " + method_str
					+ " not found on rpcServer.");
		}//end if method==NULL
		else
		{
			_exeSuccess
					= method->execute(_jsonReq, _jsonResp, _addr, _exeError);
		}//end if method!=NULL
	} catch (runtime_error &err)
	{
		_exeError = err.what();
		_jsonResp[Const::ID] = _jsonReq["id"];
		_jsonResp[Const::ERROR] = _exeError;
		_jsonResp[Const::RESULT] = Value::null;

		_exeSuccess = false;
	} catch (JsonRpcException &exception)
	{
		_exeError = exception.what();
		_jsonResp[Const::ID] = _jsonReq["id"];
		_jsonResp[Const::ERROR] = _exeError;
		_jsonResp[Const::RESULT] = Value::null;

		_exeSuccess = false;
	} catch (...)
	{
		_exeError = "unknown error.";
		_jsonResp[Const::ID] = _jsonReq["id"];
		_jsonResp[Const::ERROR] = _exeError;
		_jsonResp[Const::RESULT] = Value::null;

		_exeSuccess = false;
	}
}

void Conn::close()
{
	_server->getNetLogger().info("bye client fd=%d", _sock);
	::close(_sock);
}

//是否可以安全删除了？(JobPoll完全执行完毕)
bool Conn::isSafeDel()
{
	return _safeDel;
}

//是否可以安全删除了？(JobPoll完全执行完毕)
void Conn::setSafeDel(bool del)
{
	_safeDel = del;
}
